﻿using AutoMapper;
using Sheep_Breeding.Domain;
using Sheep_Breeding.ErrorCode;
using Sheep_Breeding.Infeartructure;
using Sheep_Breeding.Write.Api.DTOSheep;
using Sheep_Breeding.Write.Api.OperationServices.IServices;

namespace Sheep_Breeding.Write.Api.OperationServices.Services
{
    /// <summary>
    /// 羊场管理实现类
    /// </summary>
    public class SheepfarmServices : ISheepfarmServices
    {
        private readonly ILogger<SheepfarmServices> logger;
        private readonly IBaseRepository<Sheepfarm_management> sheepfarm_management;
        private readonly IMapper mapper;
        private readonly IBaseRepository<BuildingManagement> buildingManagement;
        private readonly IBaseRepository<Field_management> field_management;


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public SheepfarmServices(ILogger<SheepfarmServices> logger, IBaseRepository<Sheepfarm_management> sheepfarm_management, IMapper mapper,IBaseRepository<BuildingManagement> buildingManagement,IBaseRepository<Field_management> field_management)
        {
            this.logger = logger;
            this.sheepfarm_management = sheepfarm_management;
            this.mapper = mapper;
            this.buildingManagement = buildingManagement;
            this.field_management = field_management;
        }


        /// <summary>
        /// 新增羊场信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> CreateSheepfarm(CreateSheepfarmDto dto)
        {
            try
            {
                logger.LogInformation("新增羊场信息操作");

                var res = new ApiResult();

                var info = mapper.Map<Sheepfarm_management>(dto);

                var model = await sheepfarm_management.AddAsyn(info);
                if (model > 0)
                {
                    res.success("羊场信息新增成功");
                    return res;
                }


                return res;

            }
            catch (Exception ex)
            {

                logger.LogError("羊场信息报错" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 羊场信息删除操作
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> DeleteSheepfarm(DeleteSheepfarmDto dto)
        {
            try
            {
                logger.LogInformation("删除羊场信息操作");

                var res = new ApiResult();

                var info = await sheepfarm_management.GetValue(x => x.SheepfarmId.Equals(dto.SheepfarmId));
                if (info != null)
                {
                    info.IsDelete = true;

                    var model = await sheepfarm_management.Update(info);

                    if (model > 0)
                    {
                        res.success("羊场数据删除成功");
                        return res;
                    }
                }


                return res;
            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 修改羊场信息
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> UpdateSheepfarm(UpdateSheepfarmDto dto)
        {
            try
            {
                logger.LogInformation("修改羊场信息操作");

                var res = new ApiResult();


                var info = mapper.Map<Sheepfarm_management>(dto);

                var model = await sheepfarm_management.Update(info);

                if (model > 0)
                {
                    res.success("修改羊场信息成功");
                    return res;
                }

                return res;
            }
            catch (Exception ex)
            {

                logger.LogError("修改羊场信息报错" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 更新羊场状态（启用/禁用）
        /// </summary>
        /// <param name="dto">更新状态DTO</param>
        /// <returns>返回操作结果</returns>
        public async Task<ApiResult> UpdateSheepfarmStatus(UpdateSheepfarmStatusDto dto)
        {
            try
            {
                logger.LogInformation("更新羊场状态操作");

                var res = new ApiResult();

                var entity = await sheepfarm_management.GetValue(x => x.SheepfarmId.Equals(dto.SheepfarmId));
                if (entity == null)
                {
                    res.msg = "未找到指定的羊场信息";
                    return res;
                }

                entity.Status = dto.Status;
                entity.ModifyTime = DateTime.Now;

                var model = await sheepfarm_management.Update(entity);
                if (model > 0)
                {
                    res.success($"羊场{(dto.Status ? "启用" : "禁用")}成功");
                    return res;
                }

                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"更新羊场状态异常：{ex.Message}");
                throw ex;
            }
        }


        /// <summary>
        /// 创建栋舍管理信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> CreateBuildingManagement(CreateBuildingManagementDto dto)
        {
            try
            {
                logger.LogInformation("创建栋舍管理信息操作");

                var res = new ApiResult();

                

                var info = mapper.Map<BuildingManagement>(dto);

                info.Create_time = DateTime.Now;

                info.Modifier = string.Empty;

                var model = await buildingManagement.AddAsyn(info);

                if (model > 0)
                {
                    res.success("创建栋舍管理信息成功");
                    return res;
                }

                return res;


            }
            catch (Exception ex)
            {

                logger.LogError("创建栋舍管理信息操作异常" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 修改栋舍管理信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> UpdateBuildingManagement(UpdateBuildingManagementDto dto)
        {
            try
            {
                logger.LogInformation("修改栋舍管理操作");

                var  res=new ApiResult();

                var info=mapper.Map<BuildingManagement>(dto);

                info.Modify_time=DateTime.Now;

        var model = await buildingManagement.Update(info);

                if (model > 0)
                {
                    res.success("修改栋舍管理信息成功");
                    return res;
                }

                return res;
            }
            catch (Exception ex)
            {

                logger.LogError("修改栋舍管理异常" + ex.Message);
                throw ex;
            }
        }
        /// <summary>
        /// 删除栋舍管理数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteBuildingManagement(DeleteBuildingManagementDto dto)
        {
            try
            {
                logger.LogInformation("删除栋舍管理数据操作");
                var res=new ApiResult();

                var info = await buildingManagement.GetValue(x=>x.BuildingId.Equals(dto.BuildingId));
                if (info != null)
                {
                    info.IsDelete = true;

                    var model = await buildingManagement.Update(info);
                    if (model > 0)
                    {
                        res.success("栋舍信息删除成功");
                        return res;
                    }
                }

                return res;
            }
            catch (Exception ex)
            {

                logger.LogError("删除栋舍管理数据异常" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 更新栋舍状态（启用/禁用）
        /// </summary>
        /// <param name="dto">更新状态DTO</param>
        /// <returns>返回操作结果</returns>
        public async Task<ApiResult> UpdateBuildingManagementStatus(UpdateBuildingManagementStatusDto dto)
        {
            try
            {
                logger.LogInformation("更新栋舍状态操作");

                var res = new ApiResult();

                var entity = await buildingManagement.GetValue(x => x.BuildingId.Equals(dto.BuildingId));
                if (entity == null)
                {
                    res.msg = "未找到指定的栋舍信息";
                    return res;
                }

                entity.Status = dto.Status;
                entity.Modify_time = DateTime.Now;

                var model = await buildingManagement.Update(entity);
                if (model > 0)
                {
                    res.success($"栋舍{(dto.Status ? "启用" : "禁用")}成功");
                    return res;
                }

                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"更新栋舍状态异常：{ex.Message}");
                throw ex;
            }
        }

        /// <summary>
        /// 创建栏位管理
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> CreateField_management(CreateField_managementDto dto)
        {
            try
            {
                logger.LogInformation("创建栏位管理操作");

                var res=new ApiResult();

                var info = mapper.Map<Field_management>(dto);

                var model = await field_management.AddAsyn(info);

                if (model > 0)
                {
                    res.success("创建栏位管理成功");
                    return res;
                }

                return res;

            }
            catch (Exception ex)
            {

                logger.LogError("创建栏位管理异常" + ex.Message);
                throw ex;
            }
        }
        /// <summary>
        /// 更新栏位管理
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> UpdateField_management(UpdateField_managementDto dto)
        {
            try
            {
                logger.LogInformation("更新栏位管理操作");
                var res=new ApiResult();
                var info=mapper.Map<Field_management>(dto);

                
                var model = await field_management.Update(info);

                 if (model > 0)
                {
                    res.success("更新栏位管理成功");
                    return res;
                }

                 return res;
            }
            catch (Exception ex)
            {

                logger.LogError("更新栏位管理异常" + ex.Message);
                throw ex;
            }
        }
        /// <summary>
        /// 删除栏位管理 
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> DeleteField_management(DeleteField_managementDto dto)
        {
            try
            {
                logger.LogInformation("删除栏位管理操作");

                var res=new ApiResult();

                var info = await field_management.GetValue(x => x.Field.Equals(dto.Field));
                if (info!=null)
                {
                    info.IsDelete = true;

                    var model = await field_management.Update(info);
                    if (model > 0)
                    {
                        res.success("删除栏位管理成功");
                        return res;
                    }
                }

                return res;
            }
            catch (Exception ex)
            {

                logger.LogError("删除栏位管理异常" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 批量删除羊场信息
        /// </summary>
        /// <param name="dto">批量删除DTO</param>
        /// <returns>返回操作结果</returns>
        public async Task<ApiResult> BatchDeleteSheepfarms(BatchDeleteSheepfarmsDto dto)
        {
            try
            {
                logger.LogInformation("批量删除羊场信息操作");

                var res = new ApiResult();

                if (dto.SheepfarmIds == null || !dto.SheepfarmIds.Any())
                {
                    res.msg = "删除的ID列表不能为空";
                    return res;
                }

                var entities =sheepfarm_management.Getlist().Where(x => dto.SheepfarmIds.Contains(x.SheepfarmId));
                if (!entities.Any())
                {
                    res.msg = "未找到要删除的羊场信息";
                    return res;
                }

                foreach (var entity in entities)
                {
                    entity.IsDelete = true;
                    entity.ModifyTime = DateTime.Now;
                }

                var model = await sheepfarm_management.BatchUpdate(entities.ToList());
                if (model > 0)
                {
                    res.success("批量删除羊场信息成功");
                    return res;
                }

                return res;
            }
            catch (Exception ex)
            {
                logger.LogError("批量删除羊场信息异常：" + ex.Message);
                throw ex;
            }
        }
       
        /// <summary>
        /// 批量删除栋舍信息
        /// </summary>
        /// <param name="dto">批量删除DTO</param>
        /// <returns>返回操作结果</returns>
        public async Task<ApiResult> BatchDeleteBuildingManagement(BatchDeleteBuildingManagementDto dto)
        {
            try
            {
                logger.LogInformation("批量删除栋舍信息操作");

                var res = new ApiResult();

                if (dto.BuildingIds == null || !dto.BuildingIds.Any())
                {
                    res.msg = "删除的ID列表不能为空";
                    return res;
                }

                var entities = buildingManagement.Getlist().Where(x => dto.BuildingIds.Contains(x.BuildingId));
                if (!entities.Any())
                {
                    res.msg = "未找到要删除的栋舍信息";
                    return res;
                }

                foreach (var entity in entities)
                {
                    entity.IsDelete = true;
                    entity.Modify_time = DateTime.Now;
                }

                var model = await buildingManagement.BatchUpdate(entities.ToList());
                if (model > 0)
                {
                    res.success("批量删除栋舍信息成功");
                    return res;
                }

                return res;
            }
            catch (Exception ex)
            {
                logger.LogError("批量删除栋舍信息异常：" + ex.Message);
                throw ex;
            }
        }
    }
}
